// order//order/orderList/index.js
const app = getApp();
const util = require('../../../utils/util.js');
const utils = require('../../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    CurrentPage: 1,
    loadingMoreHidden: 1,
    CurrentPageCoupon: 1,
    loadingMoreHiddenCoupon: 1,
    isLoading: true,
    type: 1, //1配送服务2优惠券/套餐, 3 供货订单, 4 代卖订单
    tagindex: 1, //1全部2待付款3待使用4待发货5已完成6退款售后
    tagindex2: 1,//1全部2待消费3已完成4退款售后
    orderList: [],
    totalStock: 0, //待发货数量
    showConfirm: false,
    currentOid: 0,
    tips: '',
    shipState: 0,
    top: 20,
    createUid: 0,
    shipType: 0,  //配送类型： 1 快递配送, 2 同城配送
    shipCoId: 0 //配送公司ID
  },
  //派单(企动快送)
  // allotOrder: function (e) {
  //   let oid = e.currentTarget.dataset.oid;
  //   wx.navigateTo({
  //     url: '../allotOrder/index?oid=' + oid,
  //   })
  // },
  //取消配送
  cancelDlevery: function (e) {
    let that = this;
    let oid = e.currentTarget.dataset.oid;
    utils.confirm('确定要取消配送,并退回配送费吗？',()=>{
      wx.request({
        url: app.globalData.host + '/api/ship/cancelOrder?oid=' + oid,
        success: function (res) {
          if (res.data.Code == 0) {
            utils.showToast('取消成功');
            that.getOrderList();
          } else {
            utils.showModal( res.data.Message);       
          }
        },
      })
    })    
  },
  // cancelDlevery: function (e) {
  //   let that = this;
  //   let oid = e.currentTarget.dataset.oid;
  //   wx.request({
  //     url: app.globalData.host + '/api/porder/OrderByOid?oid=' + oid,
  //     success: function (res) {
  //       if (res.data.Code == 0) {
  //         let shipState = 0;
  //         let tips = '该订单未曾派单至企动快送';
  //         if (res.data.Data) {
  //           shipState = res.data.Data.ShipState;
  //           let money = res.data.Data.Shipfee + res.data.Data.Tip;
  //           tips = '退款金额：' + money + ' 元';
  //           if (res.data.Data.ShipState == 5) {
  //             tips = '您的配送费已退，不能重复申请';
  //           }
  //           that.data.shipState = shipState;
  //         }
  //         that.data.currentOid = oid;
  //         that.setData({
  //           tips: tips,
  //           showConfirm: !that.data.showConfirm
  //         })

  //       } else {
  //         wx.showModal({
  //           title: '提示',
  //           content: res.data.Message,
  //           showCancel: false
  //         })
  //       }
  //     },
  //   })
  // },

  sureConfirm: function () {
    let that = this;
    if (that.data.shipState != 5) {
      wx.request({
        url: app.globalData.host + '/api/porder/CacelOrderByShop?oid=' + that.data.currentOid,
        success: function (res) {
          that.setData({
            showConfirm: !that.data.showConfirm
          })
          if (res.data.Code == 0) {
            wx.showToast({
              title: '退款成功',
              mask: true
            })
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.Message,
              showCancel: false
            })
          }
        }
      })
    }else{
      that.setData({
        showConfirm: !that.data.showConfirm
      })
    }

  },

  closeDialog: function () {
    this.setData({
      showConfirm: !this.data.showConfirm
    })
  },

  changeType: function (e) {
    let type = e.currentTarget.dataset.type;
    this.setData({
      type: type,
      tagindex: 1,
      tagindex2: 1,
      isLoading: true,
      CurrentPage: 1,
      totalStock: 0
    })
    if(type == 2){
      this.getOrderListCoupon();
    }else{
      this.getOrderList();
    }
  },

  changeTag: function (e) {
    let tagindex = e.currentTarget.dataset.tagindex;
    this.setData({
      tagindex: tagindex,
      CurrentPage: 1
    })
    this.getOrderList();
  },
  changeTagCoupon: function (e) {
    let tagindex2 = e.currentTarget.dataset.tagindex2;
    this.setData({
      tagindex2: tagindex2,
      CurrentPageCoupon: 1
    })
    this.getOrderListCoupon();
  },

  // 获取订单列表
  getOrderList: function () {
    let that = this;
    let state = 0;
    let createUid = app.globalData.userInfo.Uid;    
    switch(that.data.tagindex){
      case '2': state = 20; break;  //待付款
      case '3': state = 80; break;  //待发货
      case '4': state = 100; break; //待收货
      case '5': state = 120; break; //已完成
      case '6': state = 180; break; //退款售后
    }
    
    let path = '/api/order/orderlist?storeid=' + app.globalData.storeId + '&orderState=' + state + '&showproduct=1&showuser=1&pageNumber=' + that.data.CurrentPage + '&cateIds=195';    
    if(that.data.type == 3){
      path += '&jump=12,13';                       //供货订单
    }
    if(that.data.type == 4){
      path += '&jump=12,13&saleUid=' + createUid;  //代卖订单
      createUid = 0;
    }
    path += '&createUid=' + createUid;  
    if(that.data.CurrentPage <= 1){
      that.setData({orderList:[]});
    }   
    
    wx.request({
      url: app.globalData.host + path,
      success: function (res) {
        that.setData({
          isLoading: false,
          createUid: createUid,
        })
        if(res.data.Code != 0){
          utils.showModal(res.data.Message); return;
        }
        let orderList = res.data.Data.OrderList;
        let productList = res.data.Data.ProductList;
        let userList = res.data.Data.UserList;
        let totalStock = res.data.Data.PageModel.TotalCount;
        let printList = res.data.Data.PrintList;
        let diningTableList = res.data.Data.DiningTableList;     

        for (let i = 0; i < orderList.length; i++) {
          orderList[i].printNo = 0;//自取号
          orderList[i].productList = [];
          orderList[i].userInfo = {}
          orderList[i].buyCount = 0;
          orderList[i].sid = orderList[i].sid.trim();

          for (let j = 0; j < productList.length; j++) {
            if (orderList[i].oid == productList[j].Oid) {
              if (productList[j].ShowImg.indexOf('ps') != -1) {
                productList[j].ShowImg = utils.formatAvaterByProHead(productList[j].ShowImg);
              } else {
                productList[j].ShowImg = utils.formatAvater(productList[j].ShowImg, 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/');
              }
              orderList[i].buyCount += productList[j].BuyCount;
              orderList[i].productList.push(productList[j]);
            }
          }
          for (let k = 0; k < userList.length; k++) {
            if (orderList[i].uid == userList[k].Uid) {
              orderList[i].userInfo.nickName = userList[k].NickName;
              orderList[i].userInfo.Avatar = userList[k].Avatar;
              break;
            }
          }
          if (printList && printList.length > 0) {
            for (let m = 0; m < printList.length; m++) {
              if (orderList[i].oid == printList[m].Oid) {
                orderList[i].printNo = printList[m].PrintNo;
                break;
              }
            }
          }
          if (diningTableList && diningTableList.length > 0) {
            for (let n = 0; n < diningTableList.length; n++) {
              if (orderList[i].sid.trim() == diningTableList[n].Id) {
                orderList[i].tableNumber = diningTableList[n].TableNumber;
                orderList[i].tableName = diningTableList[n].Name;
                break;
              }
            }
          }
        }
      
        if (that.data.CurrentPage != 1) {
          var preGoods = that.data.orderList
          orderList = preGoods.concat(orderList);
        }
        that.setData({
          orderList: orderList,
          loadingMoreHidden: res.data.Data.PageModel.TotalPages
        })
        if (state == 80) {
          that.setData({
            totalStock: totalStock
          })
        }
      }
    })
  },

  // 获取代金券/套餐订单列表
  getOrderListCoupon: function () {
    let that = this;
    let state = 0;
    switch(that.data.tagindex2){
      case 2: state = 80; break;  //待消费
      case 3: state = 120; break; //已完成
      case 4: state = 180; break; //退款售后
    }
    wx.request({
      url: app.globalData.host + '/api/order/orderlist?storeid=' + app.globalData.storeId + '&createUid=' + app.globalData.userInfo.Uid + '&orderState=' + state + '&showproduct=1' + '&showuser=1&pageNumber=' + that.data.CurrentPageCoupon + '&cateIds=375,376,377,378' + '&showExtend=1',
      success: function (res) {
        that.setData({
          isLoading: false
        })
        if (res.data.Code == 0) {
          let orderList = res.data.Data.OrderList;
          let productList = res.data.Data.ProductList;
          let userList = res.data.Data.UserList;
          let extendList = res.data.Data.ExtendList;
          let ProductDetailList = res.data.Data.ProductDetailList;
          if (orderList.length > 0) {
            for (let i = 0; i < orderList.length; i++) {
              orderList[i].productList = [];
              orderList[i].userInfo = {}
              orderList[i].buyCount = 0;
              orderList[i].expireTime = '';

              for (let j = 0; j < productList.length; j++) {
                if (orderList[i].oid == productList[j].Oid) {
                  orderList[i].buyCount += productList[j].BuyCount;
                  if (productList[j].ShowImg.indexOf('ps') != -1) {
                    productList[j].ShowImg = utils.formatAvaterByProHead(productList[j].ShowImg);
                  } else {
                    productList[j].ShowImg = utils.formatAvater(productList[j].ShowImg, 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/');
                  }
                  orderList[i].productList.push(productList[j]);
                }
              }
              let proList = orderList[i].productList;
              for (let m = 0; m < extendList.length; m++) {
                if (extendList[m].Pid == proList[0].Pid) {
                  orderList[i].expireTime = extendList[m].UseEndTime.substr(0, 10);
                  break;
                }
              }
              if (ProductDetailList && ProductDetailList.length > 0) {
                for (let m = 0; m < ProductDetailList.length; m++) {
                  if (ProductDetailList[m].Pid == proList[0].Pid) {
                    orderList[i].shadowPrice = ProductDetailList[m].ShadowPrice;
                    break;
                  }
                }
              }

              for (let k = 0; k < userList.length; k++) {
                if (orderList[i].uid == userList[k].Uid) {
                  orderList[i].userInfo.nickName = userList[k].NickName;
                  orderList[i].userInfo.Avatar = userList[k].Avatar;
                  break;
                }
              }
            }
          }
          if (that.data.CurrentPageCoupon != 1) {
            var preGoods = that.data.orderList
            orderList = preGoods.concat(orderList);
          }
          that.setData({
            orderList: orderList,
            loadingMoreHiddenCoupon: res.data.Data.PageModel.TotalPages
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  // 获取待发货数量
  getOrderStocking: function () {
    let that = this;
    let state = 80;
    wx.request({
      url: app.globalData.host + '/api/order/orderlist?storeid=' + app.globalData.storeId + '&createUid=' + app.globalData.userInfo.Uid + '&orderState=' + state + '&showproduct=1' + '&showuser=1&pageNumber=' + that.data.CurrentPage + '&cateIds=195',
      success: function (res) {
        if (res.data.Code == 0) {
          let totalStock = res.data.Data.PageModel.TotalCount;
          that.setData({
            totalStock: totalStock
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  toDetail: function (e) {
    let oid = e.currentTarget.dataset.oid;
    let uid = e.currentTarget.dataset.uid;
    let isCoupon = e.currentTarget.dataset.iscoupon;
    wx.navigateTo({
      url: '../orderDetail/index?oid=' + oid + '&uid=' + uid + '&isBoss=1&iscoupon=' + isCoupon,
    })
  },
   
  // 发货
  sendOrderProduct: function (e) {
    let that = this;
    let oid = e.currentTarget.dataset.oid;
    var shipCoId = that.data.shipCoId;  
    var shipType = that.data.shipType;  
    var shipName = '';
    //快递方式发货
    if(shipType == 1){
      wx.navigateTo({
        url: '/pages/h5page/index?url=' + encodeURIComponent(app.globalData.webhost + 'order-send.html?oid=' + oid+'&uid=' + app.globalData.userInfo.Uid),
      });
      return;
    }

    if(shipCoId == 0){
      utils.showModal('未完善配送方式，请前往[设置-外卖设置-配送方式]页面完善');
      return;
    }  
    //企动快送
    if(shipCoId == 26) {
      wx.navigateTo({
        url: '../allotOrder/index?oid=' + oid,
      })
      return;
    }

    //骑手配送方式发货
    switch(shipCoId){
      case 17: shipName='达达配送'; break; 
      case 28: shipName='顺丰同城'; break; 
      case 26: shipName='企动快送'; break; 
      case 11: shipName='商家配送'; break; 
    }   

    wx.showModal({
      title: '提示',
      content: '发货方式为' + shipName + '，是否确认发货?',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.host + '/api/Order/SendOrderProduct?uid=' + app.globalData.userInfo.Uid + '&oid=' + oid + '&shipCoId=' + shipCoId + '&shipSn=711688',
            success: function (res) {
              if (res.data.Code == 0) {
                util.showToast('发货成功');                
                that.getOrderList();
              } else {
                util.showModal(res.data.Message);                
              }
            }
          })
        }
      }
    })
  },

  // 收货
  receiveOrder: function (e) {
    let that = this;
    let oid = e.currentTarget.dataset.oid;
    wx.showModal({
      title: '提示',
      content: '是否确认收货？',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.host + '/api/Order/ReceiveOrder?uid=' + app.globalData.userInfo.Uid + '&oid=' + oid,
            success: function (res) {
              if (res.data.Code == 0) {
                wx.showToast({
                  mask: true,
                  title: '订单已完成',
                  duration: 500
                })
                that.getOrderList();
              } else {
                wx.showModal({
                  title: '提示',
                  content: res.data.Message,
                  showCancel: false
                })
              }
            }
          })
        }
      }
    })
  },
  //加小费
  addTip: function(e){
    let oid = e.currentTarget.dataset.oid;
    wx.navigateTo({
      url: '../allotOrder/index?action=addTip&oid=' + oid,
    })
  },
  // 确认/拒绝退款（1同意0拒绝）
  sureRefund: function (e) {
    let that = this;
    let oid = e.currentTarget.dataset.oid; //退款申请id
    let state = e.currentTarget.dataset.state;
    let mesg = '是否确认退款?'
    if (state == 0) {
      mesg = '是否拒绝退款?'
    }
    wx.showModal({
      title: '提示',
      content: mesg,
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.host + '/api/OrderAfter/GetAfterOrder?oid=' + oid,
            success: function (res) {
              if (res.data.Code == 0) {
                if (res.data.Data.ASId) {
                  that.confirmRefund(res.data.Data.ASId, state);
                } else {
                  wx.showModal({
                    title: '提示',
                    content: '退款失败',
                    showCancel: false
                  })
                }

              } else {
                wx.showModal({
                  title: '提示',
                  content: res.data.Message,
                  showCancel: false
                })
              }
            }
          })
        }
      }
    })
  },

  confirmRefund: function (asid, state) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/OrderAfter/CheckRefund?asId=' + asid + '&uid=' + app.globalData.userInfo.Uid + '&state=' + state,
      success: function (res) {
        if (res.data.Code == 0) {
          wx.showToast({
            mask: true,
            title: '退款审核完成'
          })
          that.getOrderList();
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  // 手动打印订单
  printOrder: function (e) {
    let oid = e.currentTarget.dataset.oid;
    wx.request({
      url: app.globalData.host + '/api/Print/Print?oid=' + oid,
      success: function (res) {
        if (res.data.Code != 0) {

        }
      }
    })
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getOrderList();
    this.getOrderStocking();
    this.getShip();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(app.globalData.userInfo){
      this.data.createUid = app.globalData.userInfo.Uid;
    }
  },
  // 加载更多
  loadMore: function (e) {
    var that = this;
    if (that.data.loadingMoreHidden > 1 && that.data.CurrentPage < that.data.loadingMoreHidden) {
      var currPage = that.data.CurrentPage;
      that.setData({
        CurrentPage: currPage + 1
      })
      that.getOrderList();
    } else {
      return
    }
  },

  // 加载更多(优惠券/套餐)
  loadMoreCoupon: function (e) {
    var that = this;
    if (that.data.loadingMoreHiddenCoupon > 1 && that.data.CurrentPageCoupon < that.data.loadingMoreHiddenCoupon) {
      var currPage = that.data.CurrentPageCoupon;
      that.setData({
        CurrentPageCoupon: currPage + 1
      })
      that.getOrderListCoupon();
    } else {
      return
    }
  },

  onReachBottom: function () {
    if(this.data.type == 1){
      this.loadMore()
    }else{
      this.loadMoreCoupon();
    }
  },

  onPageScroll: function (e) {
    let top = parseInt(e.scrollTop);
    this.setData({
      top: top + 20
    })
  },
  
  toExport :function(){
    let state = 0 // 1 供货订单统计, 2 代卖订单统计
    state = this.data.type == 3 ? 1 : state;  
    state = this.data.type == 4 ? 2 : state;
    wx.navigateTo({
      url: '/order/order/orderExport/index?state=' + state,
    })
  },  
  toReport :function(){
    let state = 0 // 1 供货订单统计, 2 代卖订单统计
    state = this.data.type == 3 ? 1 : state;  
    state = this.data.type == 4 ? 2 : state;
    wx.navigateTo({
      url: '/merchant/supply/orderReport/index?state=' + state,
    })
  },
   
  //配送方式
  getShip: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/ship/getship?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0 && res.data.Data) {
          that.setData({
            shipCoId: res.data.Data.ShipCoId,
            shipType: res.data.Data.ShipType
          })
        }
      }
    })
  }
})